<template>
    <div class="box">
        <header class="header">
            <van-nav-bar title="购物车" left-arrow @click-left="$router.back()" />
        </header>
        <div class="content">
            <van-empty v-if="cartList.length == 0"
                image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" image-size="80"
                description="购物车空空如也，去逛逛吧~" />
            <van-swipe-cell v-else v-for="item in cartList" :key="item.id">
                <van-card :num="item.count" :price="item.price" :title="item.title" :thumb="item.image">
                    <template #tag>
                        <van-checkbox v-model="item.checked"></van-checkbox>
                    </template>
                    <template #footer>
                        <van-stepper v-model="item.count" />
                    </template>
                </van-card>
                <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="onDelete(item.id)" />
                </template>
            </van-swipe-cell>
        </div>
    </div>
    <footer class="footer">
        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="$router.push('/order')">
            <van-checkbox v-model="allChecked">全选</van-checkbox>
        </van-submit-bar>
    </footer>
</template>
<script>
import { mapState, mapGetters } from 'vuex'
export default {
    computed: {
        ...mapState(['cartList']),
        ...mapGetters(['totalPrice']),
        allChecked: {
            get() {
                // 获取allChecked的值 --- 当列表中所有数据被勾选，allChecked就是true; 只要列表中至少有一个没被勾选上，allChecked就是false
                // 如果购物车列表是空的 allChecked就是false
                if (this.cartList.length == 0) {
                    return false
                } else {
                    return this.cartList.every(item => item.checked == true)
                }
            },
            set(newValue) {
                // newValue 代表的是allChecked最新的值  全选按钮被勾上时，newValue是true; 全选按钮没被勾上时，newValue是false
                this.$store.commit('changeChecked', newValue)
            }

        }
    },

    methods: {
        onDelete(id) {
            // 修改cartList
            this.$store.commit('deleteItem', id)
        }
    }

}

</script>
<style lang="scss" scoped>
.delete-button {
    height: 100%;
}
</style>